package org.linlinjava.litemall.wx.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.RequiredArgsConstructor;
import org.linlinjava.litemall.core.notify.AwsNotifyService;
import org.linlinjava.litemall.core.util.RegexUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallDistributionDetail;
import org.linlinjava.litemall.db.domain.LitemallDistributionLog;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.service.LitemallDistributionDetailService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.wx.annotation.LogAnno;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.linlinjava.litemall.wx.service.WxRewardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.linlinjava.litemall.wx.util.WxResponseCode.*;

/**
 * wx奖励控制器
 *
 * @author yliyun
 * @program: litemall
 * @description: 分销
 * @author: chenyu
 * @create: 2022-03-18 19:06
 * @date 2022/09/14
 */
@RestController
@RequestMapping("/wx/reward")
@RequiredArgsConstructor
@Validated
public class WxRewardController {

    /**
     * wx奖励服务
     */
    private final WxRewardService wxRewardService;

    /**
     * 用户服务
     */
    private final LitemallUserService userService;

    private final LitemallDistributionDetailService litemallDistributionDetailService;


    /**
     * aws通知服务
     */
    private AwsNotifyService awsNotifyService;


    /**
     * 奖励细节
     *
     * @param userId 用户id
     * @return {@link Object}
     */
    @GetMapping("rewardDetail")
    @LogAnno
    public Object rewardDetail(@LoginUser Integer userId){
      if(userId == null){
        return ResponseUtil.unlogin();
      }
      return wxRewardService.rewardDetail(userId);
    }

    /**
     * 发送邀请
     *
     * @param userId  用户id
     * @param contact 联系
     * @return {@link Object}
     */
    @PostMapping("sendInvitation")
    @LogAnno
    public Object sendInvitation(@LoginUser Integer userId,String contact){
        //未登录
        if(userId == null){
           return ResponseUtil.unlogin();
         }
        //邀请人
         LitemallUser user =  userService.queryMobileOrEmail(contact);
         if(user != null){
           return ResponseUtil.fail(USER_EXIST,"用户已存在");
         }
        //用户是否已经被同一个人邀请过
        /*List<LitemallDistributionDetail> distributionDetails = litemallDistributionDetailService.selectJoinList(LitemallDistributionDetail.class,new MPJLambdaWrapper<LitemallDistributionDetail>()
                .selectAll(LitemallDistributionDetail.class)
                .leftJoin(LitemallDistributionLog.class,LitemallDistributionLog::getId,LitemallDistributionDetail::getDisLogId)
                .eq(LitemallDistributionDetail::getRegisterUsername, contact)
                .eq(LitemallDistributionLog::getUserId, userId));
         if(CollUtil.isNotEmpty(distributionDetails)){
             return ResponseUtil.fail(USER_HAVE_INVITED,"用户已经邀请过,请勿重复邀请");
         }*/
         //记录邀请
        //发送邀请
        return RegexUtil.isEmailExact(contact)?wxRewardService.sendEmail(userId,contact)
                :(RegexUtil.isMobileValid(contact)?wxRewardService.sendMobile(userId,contact):ResponseUtil.fail(EMAIL_OR_MOBILE_ERROR,"邮箱或手机号不正确"));
        /*if(RegexUtil.isEmailExact(contact)){
             //检查邮箱规范
           return wxRewardService.sendEmail(userId,contact);
         }else if(RegexUtil.isMobileValid(contact)){
             //检查手机号码规范
             return wxRewardService.sendMobile(userId,contact);
         }else{
            return ResponseUtil.fail(EMAIL_OR_MOBILE_ERROR,"邮箱或手机号不正确");
        }*/
    }


    /**
     * 通过手机发送邀请
     *
     * @param userId 用户id
     * @param mobile 移动
     * @return {@link Object}
     */
    @PostMapping("sendInvitationByMobile")
    @LogAnno
    public Object sendInvitationByMobile(@LoginUser Integer userId,String mobile){
      if(userId == null){
        return ResponseUtil.unlogin();
      }
    //用户是否已经被同一个人邀请过
    /*List<LitemallDistributionDetail> distributionDetails = litemallDistributionDetailService.selectJoinList(LitemallDistributionDetail.class,new MPJLambdaWrapper<LitemallDistributionDetail>()
            .selectAll(LitemallDistributionDetail.class)
            .leftJoin(LitemallDistributionLog.class,LitemallDistributionLog::getId,LitemallDistributionDetail::getDisLogId)
            .eq(LitemallDistributionDetail::getRegisterUsername, mobile)
            .eq(LitemallDistributionLog::getUserId, userId));
    if(CollUtil.isNotEmpty(distributionDetails)){
        return ResponseUtil.fail(USER_HAVE_INVITED,"用户已经邀请过,请勿重复邀请");
    }*/
    return wxRewardService.sendMobile(userId,mobile);
    }

    /**
     * 检查电话
     *
     * @param phone 电话
     * @return boolean
     */
    public boolean checkPhone(String phone){
    Pattern p = Pattern.compile("^[1](([3-9][\\d])|([4][5,6,7,8,9])|([6][5,6])|([7][3,4,5,6,7,8])|([9][8,9]))[\\d]{8}$");
    return p.matcher(phone).matches()?true:false;
  }


    /**
     * 检查电子邮件
     *
     * @param email 电子邮件
     * @return boolean
     */
    public boolean checkEmail(String email) {
    if (StringUtils.isEmpty(email)){
      return false;
    }
    String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
    Pattern p;
    Matcher m;
    p = Pattern.compile(regEx1);
    m = p.matcher(email);
    return m.matches()?true:false;
  }

}
